<template>
  <div class="index-box" ref="index">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <div class="search" ref="search">
          <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent class="demo-form-inline" id="searchBox">

            <el-form-item prop="telephone">
                <el-input v-model="searchForm.telephone" clearable placeholder="推荐人手机号"></el-input>
            </el-form-item>
            <el-form-item class="clearfix">
              <el-button type="primary" @click="handleSearch()" icon="el-icon-search">搜索</el-button>
              <el-button icon="el-icon-refresh" size="small" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="actionBtn" ref="actionBtn">
          <div class="actionBtnLeft">

             <el-button type="primary" @click="handleAdd()" size="small" icon="el-icon-plus">添加用户</el-button>
          </div>
         <!-- <div class="actionBtnRight">
              <MyRefresh></MyRefresh>
              <MyTableColumnSet :tableColumn.sync="tableColumn" :hideTableColumn.sync="hideTableColumn" :tableColumnType.sync="tableColumnType"></MyTableColumnSet>
          </div> -->
        </div>

        <div class="table" ref="table">
          <el-table :data="dataList" style="width: 100%;"  border :height="tableHeight" @selection-change="handleSelectionChange"  stripe v-loading="loading">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="customerId" label="编号" v-if="!hideTableColumn.includes('number')" width="200" align="center"></el-table-column>
            <el-table-column prop="name" label="头像" v-if="!hideTableColumn.includes('img')" width="80" align="center">
              <template #default="scope">
                 <el-image :src="scope.row.userface" fit="fill" v-image-preview="scope.row.userface" class="img"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="nickname" label="用户名" v-if="!hideTableColumn.includes('wxName')" align="center"></el-table-column>
           <el-table-column prop="fullname" label="真实姓名" v-if="!hideTableColumn.includes('userName')" align="center"></el-table-column>
            <el-table-column prop="telephone" label="手机号" v-if="!hideTableColumn.includes('phone')" align="center"></el-table-column>
            <el-table-column prop="name" label="实名状态" v-if="!hideTableColumn.includes('autonymName')" align="center">
              <template slot-scope="scope">
                {{scope.row.realname=='1'?"是":'否'}}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="是否为推广者" v-if="!hideTableColumn.includes('autonymName')" align="center">
              <template slot-scope="scope">
                {{scope.row.promotionFlag=='1'?"是":'否'}}
              </template>
            </el-table-column>
           <!-- <el-table-column prop="insertDate" label="加入时间" v-if="!hideTableColumn.includes('joinTime')" align="center">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.insertDate) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态"  v-if="!hideTableColumn.includes('status')" align="center">
              <template #default="scope">
                <div class="d-flex justify-center">
                  <MySwitch :value.sync="scope.row.status" :id="scope.row.status" text="启用|禁用" textValue="1|2" @changeStatus="handleChangeStatus(scope.row)" :permission="hasBtn('user:userManage:state')"></MySwitch>
                </div>
              </template>
            </el-table-column> -->
            <el-table-column prop="name" label="操作"  width="150" v-if="!hideTableColumn.includes('active')" align="center" fixed="right">
              <template #default="scope">
                <div class="verticalBtn">
                 <el-button
                    size="medium"
                    type="text"
                    icon="el-icon-view"
                    @click="handleSetSpreader(scope.$index, scope.row)"
                  >设置为推广者</el-button>
                  <el-button
                    size="medium"
                    type="text"
                    icon="el-icon-s-shop"
                    @click="handleActive(scope.$index, scope.row,'storeApply')"
                  >商家申请</el-button>
                  <!-- <el-dropdown size="medium" >
                    <span class="el-dropdown-link">
                      <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                    </span>
                    <el-dropdown-menu slot="dropdown" >
                      <el-dropdown-item @click.native="handleActive(scope.$index, scope.row,'editLevel')" v-has="'user:userManage:class'" v-show="scope.row.level!='1'">修改等级</el-dropdown-item>
                      <Evaluate :id="scope.row.customerId" :statusRow="scope.row"  text="评价记录" v-has="'user:userManage:appr'"></Evaluate>
                      <Recommend :id="scope.row.customerId" :statusRow="scope.row"  text="推荐记录" v-has="'user:userManage:rec'"></Recommend>
                      <el-dropdown-item @click.native="handleActive(scope.$index, scope.row,'join')" v-has="'user:userManage:join'">加盟申请</el-dropdown-item>
                      <Tag :tagList="scope.row.tagList" :id="scope.row.customerId"  text="用户标签" @dataInfo="dataInfo" v-has="'user:userManage:user'"></Tag>
                      <el-dropdown-item @click.native="handleActive(scope.$index, scope.row,'storeApply')" v-has="'user:userManage:deta'">{{scope.row.storeId?'商家详情':"商家申请"}}</el-dropdown-item>
                      <el-dropdown-item @click.native="handleActive(scope.$index, scope.row,'jurisdictionalLimits')" v-has="'user:userManage:area'"  v-show="scope.row.level!='1'">管辖范围</el-dropdown-item>
                      <el-dropdown-item @click.native="handleActive(scope.$index, scope.row,'joinBlacklist')" v-has="'user:userManage:joinBlacklist'">加黑名单</el-dropdown-item>
                      <el-dropdown-item @click.native="handleActive(scope.$index, scope.row,'joinWhitelist')" v-has="'user:userManage:joinWhitelist'">加白名单</el-dropdown-item>

                      <el-dropdown-item @click.native="handleActive(scope.$index, scope.row,'edit')" v-has="'user:userManage:alter'">修改</el-dropdown-item>
                      <el-dropdown-item @click.native="handleActive(scope.$index, scope.row,'editPw')" v-has="'user:userManage:editPw'">修改密码</el-dropdown-item>
                      <el-dropdown-item @click.native="handleActive(scope.$index, scope.row,'delt')" v-has="'user:userManage:del'">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown> -->
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page" ref="page">
           <MyPagination
              v-show="total"
             :total="total"
             :page.sync="searchForm.pageNum"
             :limit.sync="searchForm.pageSize"
             @pagination="dataInfo"
           />
        </div>
      </el-col>
    </el-row>

    <!-- /*设置小蜜蜂推广者*/	 -->
    <el-dialog title="设置推广者" width="600px" v-dialogDrag :visible.sync="spreaderVisible" @close="spreaderVisible = false">
      <el-form class="formDialog" label-position="right" >
          设置为推广者：<el-radio-group v-model="spreaderVal" style="padding-top:4px">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="spreaderVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleSaveSpreader" size="small" :loading="btnLoading">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 加入黑名单或者白名单 -->
    <el-dialog :title="blacklistDialogTitle" width="600px" v-dialogDrag :visible.sync="blacklistVisible" @close="blacklistVisible = false">
      <el-form class="formDialog" label-position="right"  label-width="80px" >
          <el-form-item label="原因" prop="reason" style="width: 100%;">
             <el-input type="textarea" v-model="blacklistForm.reason" autocomplete="off" rows="6" ></el-input>
           </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="blacklistVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleSubmitJoinBlackList" size="small" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- /*修改等级*/	 -->
    <el-dialog :title="dialogTitle" width="600px" v-dialogDrag :visible.sync="editLevelVisible" @close="editLevelVisible = false">
      <el-form class="formDialog" label-position="right" >
          <el-checkbox-group v-model="editLevelForm" class="d-flex flex-wrap" style="width: 100%;" size="small">
            <el-checkbox :label="item.levelId" v-for="item in levelList" style="width: 50%;margin: 10px 0 10px 0;" v-if="item.levelId!='1'">{{item.nameMoney}}</el-checkbox>
          </el-checkbox-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editLevelVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleSubmitEditLevel" size="small" :loading="btnLoading">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码 -->
    <el-dialog :title="dialogTitle" width="600px" v-dialogDrag :visible.sync="editPwVisible" @close="editPwVisible = false">
      <el-form  :model="editPwForm" status-icon :rules="editPwRules" ref="editPwForm" label-position="right" >
       <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="editPwForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="editPwForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editPwVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="editPwSubmit('editPwForm')" size="small" :loading="btnLoading">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 修改分享或推荐人手机号 -->
    <el-dialog title="修改分享或推荐人手机号" width="1000px" v-dialogDrag :visible.sync="editpTelephoneVisible" @close="editpTelephoneVisible = false">
      <p class="red">注意：如果您修改了分享或推荐人手机号，前后的数据不一致，会造成系统信息混乱，请谨慎操作！！</p>
      <p>用户<span style="color:#FF7200">{{statusRow.telephone}}</span>原分享或推荐人手机号为 <span style="color:#FF7200">{{statusRow.pTelephone}}</span></p>
      <el-form  :model="editpTelephoneForm" status-icon :rules="editpTelephoneRules" ref="editpTelephoneForm" label-position="right" >
       <el-form-item label="修改为:" prop="telphone" label-width="380px">
          <el-select v-model="editpTelephoneForm.telphone" clearable placeholder="请选择" filterable>
            <el-option
              v-for="item in pTelephoneList"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer d-flex justify-center">
        <el-button @click="editpTelephoneVisible = false" >取 消</el-button>
        <el-button type="primary" @click="editpTelephoneSubmit('editpTelephoneForm')" :loading="btnLoading">确定修改</el-button>
      </div>
      <div v-if="editpTelephoneTableList.length">
          <p class="title">修改记录信息</p>
          <el-table :data="editpTelephoneTableList" style="width: 100%;"  border    stripe >
            <el-table-column prop="createBy" label="记录号"  align="center"></el-table-column>
            <el-table-column prop="updateBy" label="系统修改人（工号）"  align="center"></el-table-column>
            <el-table-column prop="originalNumber" label="原分享或推荐人手机号" width="180"  align="center"></el-table-column>
            <el-table-column prop="successNumber" label="成功修改手机号"  align="center"></el-table-column>
            <el-table-column prop="leveName" label="修改日期"  align="center">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>

          </el-table>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import common from '@/api/api';
  import {
    getModifySuperiorList,getCustromerTel,getExistAndLevel,getAllMemberLevel,customerList,updateMemberLevel,getTagList,customerDelete,userChangeStatus,resetPwdUser,modifySuperior,addBlackList,addWhiteList,
    getCustomerDetails, getCustomerList, cancelOrSettings
  } from '@/api/getData'
  import elTableInfiniteScroll from 'el-table-infinite-scroll';
  import option from '../../common/option.js';
  import Tag from '../user/components/tag';
  import Consume from '../user/components/consume';
  import Evaluate from '../user/components/evaluate';
  import Recommend from '../user/components/recommend';

  export default {
    directives: {
      'el-table-infinite-scroll': elTableInfiniteScroll
    },
    components: {
      Tag,
      Consume,
      Evaluate,
      Recommend
    },
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.editPwForm.checkPass !== '') {
            this.$refs.editPwForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.editPwForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        loading: false,
        btnLoading: false,
        createTime:[],
        searchForm: {
          telephone:'',
          pageNum: 1,
          pageSize: 20,
        },
        total: 0,
        tableColumn:[],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/
        tableHeight:400,//table 高度
        statusList: [{
          id: '1',
          name: '已实名'
        }, {
          id: '0',
          name: '未实名'
        }],
        dataList:[],

        multipleSelection: '',
        dialogTitle: '',
        statusRow:{},/*活跃的列*/

        editLevelVisible: false,/*等级弹框*/
        editLevelForm:[],
        user: {
          id: '',
          name: '',
          remark: ''
        },
        rules: {
          name: [{
            required: true,
            name: '角色名称不能为空',
            trigger: 'blur'
          }]
        },
        editPwVisible:false,
        editPwForm:{
          pass:'',
          checkPass:'',
          customerId:''
        },
        editPwRules: {
          pass: [
            { required: true,validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { required: true,validator: validatePass2, trigger: 'blur' }
          ],
        },

        levelList:[],
        tagList:[],
        value:false,
        statusRow:{},
        editpTelephoneVisible:false,
        pTelephoneList:[],
        editpTelephoneTableList:[],
        editpTelephoneForm:{
          telphone:''
        },
        editpTelephoneRules: {
          telphone: [
            { required: true,message:'修改手机号不能为空', trigger: 'blur' }
          ]
        },
        blacklistDialogTitle:'',
        blacklistVisible:false,
        blacklistForm:{
          customerId:'',
          reason:''
        },
        joinListStatus:'',//加入黑/白名单   black黑名单   white白名单

        spreaderVisible:false,
        spreaderVal:'0',
        customerIdStatus:'',
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.dataInfo();
      //this.getSelect();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight  - this.$refs.page.offsetHeight - 55;
      })
    },
    methods: {
      handleSetSpreader(index,row){
        this.spreaderVisible = true;
        this.customerIdStatus = row.customerId;
        this.spreaderVal = row.promotionFlag+'';
      },
      async handleSaveSpreader(){
        try{
          let result = await cancelOrSettings({customerId:this.customerIdStatus,promotionFlag:this.spreaderVal})
          if (result.code == 200) {
           this.spreaderVisible = false;
           this.$message.success(result.msg);
           this.dataInfo();
          } else {
            this.$message.error(result.msg);
          }
        }catch (err) {
          console.log(err)
        }
      },
      resetSearch(){
        this.createTime = [];
        this.resetForm('searchForm');
        this.dataInfo();
      },
      /** 加入黑白名单提交 **/
      async handleSubmitJoinBlackList(){
        try{
          let result = '';
          this.joinListStatus=='black'?(result = await addBlackList(this.blacklistForm)):(result = await addWhiteList(this.blacklistForm));
          if (result.code == 200) {
           this.blacklistVisible = false;
           this.$message.success(result.msg);
           this.dataInfo();
          } else {
            this.$message.error(result.msg);
          }
        } catch (err) {
          console.log(err)
        }
      },
      /** 修改分享或推荐人手机号 **/
      editpTelephone(row,e){
        if(e.currentTarget.id == 'true'){
          this.editpTelephoneForm.telphone = row.pTelephone || '';
          this.statusRow = row;
          this.getpTelephoneList();
          this.geteditpTelephoneTableList();
          this.editpTelephoneVisible = true;
        }
      },
      /** 获取加盟会员手机号 **/
      getpTelephoneList(){
        getCustromerTel().then(res=>{ this.pTelephoneList = res.data; })
      },
      /** 获取加盟会员修改手机号记录 **/
      geteditpTelephoneTableList(){
        getModifySuperiorList({customerId: this.statusRow.customerId}).then(res=>{ this.editpTelephoneTableList = res.data; })
      },
      /** 修改分享或推荐人手机号提交 **/
      editpTelephoneSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.btnLoading = true;
             modifySuperior({customerId:this.statusRow.customerId,telphone:this.editpTelephoneForm.telphone}).then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);
                this.editpTelephoneVisible = false;
                this.dataInfo();
              } else {
                this.$message.error(result.msg);
              }
              this.btnLoading = false;
            });
          }
        })
      },
      /** 数据初始化请求动态列表数据 **/
      getSelect(){
        getAllMemberLevel().then(res=>{
          let list = res.data;
          list.map(item=>{
            item.nameMoney = item.levelId!='1'?item.name+"("+item.unionFee+"万元加盟金)":item.name
          })
          this.levelList = list;
        })
        getTagList({typeId: 2}).then(res=>{ this.tagList = res.rows; })//用户标签
      },
      async dataInfo() {
        try {
          let data = this.searchForm;
          this.loading = true;
          const result = await getCustomerList(data);
          if (result.code == 200) {
            this.total = result.total;
            this.dataList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },
      /** 不同操作按钮点击事件 **/
      handleActive(index,row,status){
        this.statusRow = row;
        if(status=='editLevel'){/*修改等级*/
            this.dialogTitle = '修改会员等级';
            this.editLevelVisible = true;
            this.editLevelForm = [];
            getExistAndLevel({customerId:this.statusRow.customerId}).then((res)=>{
              let arr = [];
              for(let i=0;i<res.data.existLevelList.length;i++){
                arr.push(res.data.existLevelList[i].levelId+'')
              }
              this.editLevelForm = arr;
            })
        }else if(status=='jurisdictionalLimits'){/*管辖范围*/
            this.$router.push({path:'/user/userArea',query:{customerId:row.customerId,name:row.nickname,phone:row.telephone}});
        }else if(status=='join'){/*加盟申请*/
          this.$router.push({path:'/user/joinApply',query:{customerId:row.customerId,type:'add'}});
        }else if(status=='userLabel'){/*用户标签*/
          this.allocationUserVisible = true;
          this.getLabelList();
        }else if(status=='storeApply'){/*商家申请*/
          let type = row.storeId?'detail':'add'
          this.$router.push({path:'/user/applyStoreNew',query:{storeId:row.storeId,type:type,customerId:row.customerId,entrance:'user'}});
        }else if(status=='detail'){/*详情*/
          this.$router.push({path:'/user/userDetail',query:{customerId:row.customerId}});
        }else if(status=='joinBlacklist'){/*加入黑名单*/
          this.blacklistDialogTitle = `把手机号为${row.telephone}的用户拉入黑名单`;
          this.blacklistVisible = true;
          this.blacklistForm.customerId = row.customerId;
          this.blacklistForm.reason = '';
          this.joinListStatus = 'black';
        }else if(status=='joinWhitelist'){/*加入白名单*/
          this.blacklistDialogTitle = `把手机号为${row.telephone}的用户拉入白名单`;
          this.blacklistVisible = true;
          this.blacklistForm.customerId = row.customerId;
          this.blacklistForm.reason = '';
          this.joinListStatus = 'white';
        }else if(status=='edit'){/*修改*/
          this.$router.push({path:'/user/addUser',query:{customerId:row.customerId}});
        }else if(status=='editPw'){/*修改密码*/
          this.dialogTitle = `修改手机号为${row.telephone}的密码`;
          this.editPwForm.customerId = row.customerId;
          this.editPwForm.pass = '';
          this.editPwForm.checkPass = '';
          this.editPwVisible = true;
        }else if(status=='delt'){/*删除*/
          this.handleDelt(row);
        }
      },
      handleSearch() {
        this.searchForm.pageNum= 1;
        this.dataInfo();
      },
      /** 删除当前列 **/
      handleDelt(row){
          this.$confirm('您确定要删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            customerDelete({customerId:row.customerId}).then((result) => {
              if (result.code == '200') {
                   this.dataInfo();
                   this.$message({
                     message: result.msg,
                     type: 'success'
                   });
               }else{
                  this.$message.error(result.msg);
               }
           });
          }).catch((err) => {
              console.log(err);
          });
      },
      /** 修改等级提交 **/
      handleSubmitEditLevel(){
        if(!this.editLevelForm.length){
          this.$message.error('请至少选中一个等级！');
          return;
        }
        this.btnLoading = true;
        updateMemberLevel({customerId:this.statusRow.customerId,levelId:this.editLevelForm.join(',')}).then((result) => {
          if (result.code == 200) {
            this.$message.success(result.msg);
            this.editLevelVisible = false;
            this.dataInfo();
          } else {
            this.$message.error(result.msg);
          }
          this.btnLoading = false;
        })
      },
      /** 修改密码提交 **/
      editPwSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.btnLoading = true;
             resetPwdUser({customerId:this.editPwForm.customerId,passWord:this.editPwForm.pass}).then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);
                this.editPwVisible = false;
              } else {
                this.$message.error(result.msg);
              }
              this.btnLoading = false;
            });
          }
        })
      },
      /** 用户角色状态修改 **/
      async handleChangeStatus(row) {
        try {
          let data = {
            customerId : row.customerId ,
            status: row.status
          }
          const result = await userChangeStatus(data);
          if (result.code == 200) {
            this.$message.success(result.msg);
          } else {
            this.$message.error(result.msg);
            row.status = !row.status;
          }
        } catch (err) {
          console.log(err)
        }
      },
      /** 添加用户 **/
      handleAdd(){
         this.$router.push({path:'/user/addUser'});
      },
      /** 表格选中状态改变 **/
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

    }
  }
</script>

<style scoped lang="scss">

  .title{
    text-align: center;
    margin:5px 0;
  }
  .el-table .el-dropdown-link{
      cursor: pointer;
      color: #61997A;
      margin-left: 5px;
  }
    .leftDialog{
      height:540px;
      overflow-y: auto;
    }
    .activeVerticalBox .activeItem{
      color:#61997A;
      cursor: pointer;
      margin: 0px;
      text-align: center;
      height:20px;
      line-height: 20px;
    }
    .activeVerticalBox .el-dropdown{
      display: flex;
      justify-content: center;
      color:#61997A;
      cursor: pointer;
    }
    .activeCheckedBox{
      border-top: 1px solid #ddd;
      padding:10px;
      height:52px;
      .el-tag{
        margin-right:10px;
      }
    }

</style>
